package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"videos/models"
)

type JsonR struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}
type VideoController struct {
	beego.Controller
}

func (c *VideoController) List() {
	var video []models.Video
	title := c.GetString("title")
	where := map[string]string{}
	if title != "" {
		where["title"] = title
	}
	err := models.DB.Model(&models.Video{}).Where(where).Find(&video).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 500,
			Msg:  "查询失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "查询成功",
			Data: video,
		}
		c.ServeJSON()
	}
}
func (c *VideoController) Add() {
	title := c.GetString("title")
	text := c.GetString("text")
	img := c.GetString("img")
	end := c.GetString("end")
	cao := c.GetString("cao")
	video := models.Video{
		Title: title,
		Text:  text,
		Img:   img,
		End:   end,
		Cao:   cao,
	}
	err := models.DB.Model(&models.Video{}).Create(&video).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 500,
			Msg:  "添加失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "添加成功",
			Data: video,
		}
		c.ServeJSON()
	}
}
func (c *VideoController) Upload() {
	file, header, err := c.GetFile("img")
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 500,
			Msg:  "请上传文件",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	defer file.Close()
	path := "static/img/" + header.Filename
	c.SaveToFile("img", path)
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 500,
			Msg:  "上传失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		imgUrl := "http://127.0.0.1:8080/" + path
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "上传成功",
			Data: imgUrl,
		}
		c.ServeJSON()
	}
}
func (c *VideoController) Del() {
	id, _ := c.GetInt("id")
	err := models.DB.Delete(&models.Video{}, id).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 500,
			Msg:  "删除失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "删除成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}
func (c *VideoController) Up() {
	id, _ := c.GetInt("id")
	title := c.GetString("title")
	text := c.GetString("text")
	img := c.GetString("img")
	end := c.GetString("end")
	cao := c.GetString("cao")
	video := models.Video{
		ID:    id,
		Title: title,
		Text:  text,
		Img:   img,
		End:   end,
		Cao:   cao,
	}
	err := models.DB.Model(&models.Video{}).Updates(&video).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 500,
			Msg:  "修改失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "修改成功",
			Data: video,
		}
		c.ServeJSON()
	}
}
